<?php

namespace Reezy\OAuth;

use GuzzleHttp\Client;
use Reezy\OAuth\Contract\OAuthInterface;
use function get_class;

abstract class OAuthBase implements OAuthInterface
{
    /**
     * The HTTP Client instance.
     *
     * @var Client
     */
    protected $httpClient;
    /**
     * The client ID.
     *
     * @var string
     */
    protected $clientId;
    /**
     * The client secret.
     *
     * @var string
     */
    protected $clientSecret;
    /**
     * The redirect url.
     *
     * @var string
     */
    protected $redirectUri;

    /**
     * @var string
     */
    protected $scope;
    /**
     * @var string
     */
    protected $name;


    /**
     * Create a new provider instance.
     *
     * @param array $config
     */
    public function __construct(array $config)
    {
        $this->clientId = $config['client_id'];
        $this->clientSecret = $config['client_secret'];
        $this->redirectUri = $config['redirect_url'] ?? '';
        $this->scope = $config['scope'] ?? '';
        $this->httpClient = new Client();
    }

    public function getClientId(): string
    {
        return $this->clientId;
    }

    public function getCodeKey(): string
    {
        return 'code';
    }


    public function isSupportSilentMode(): bool
    {
        return false;
    }

    public function getName(): string
    {
        if (empty($this->name)) {
            $className = (new \ReflectionClass(get_class($this)))->getShortName();
            $this->name = strtolower(str_replace( 'OAuth', '',$className));
        }
        return $this->name;
    }

    protected function httpPost(string $url, array $params): array
    {
        $response = $this->httpClient->post($url, [
            'headers' => ['Accept' => 'application/json'],
            'form_params' => array_filter($params)
        ]);
        return json_decode($response->getBody()->getContents(), true);
    }

    protected function httpGet(string $url, array $params): array
    {
        $response = $this->httpClient->get($url, [
            'headers' => ['Accept' => 'application/json'],
            'query' => array_filter($params)
        ]);
        return json_decode($response->getBody()->getContents(), true);
    }


    protected static function buildUrl(string $url, array $params): string
    {
        return $url . '?' . http_build_query($params, '', '&', PHP_QUERY_RFC1738);
    }

}
